package com.zero.xiaodai.controller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.zero.xiaodai.constant.ResultType;
import com.zero.xiaodai.service.ExcelService;
import com.zero.xiaodai.utils.ApkReadUtil;
import com.zero.xiaodai.utils.ExcelWriteHelper;
import com.zero.xiaodai.utils.FileListUtil;
import com.zero.xiaodai.utils.LogUtil;
import com.zero.xiaodai.utils.MongoDB;
import com.zero.xiaodai.utils.MongoProperties;
import com.zero.xiaodai.utils.ZipUtil;

import sun.misc.BASE64Decoder;

import com.google.common.base.Strings;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSFile;

@RequestMapping("common")
@Controller
public class CommonController {

	@Resource
	private ExcelService excelService;

	@RequestMapping("/upload1")
	public String upload() {
		System.out.println("upload");
		return "uploadFile";
	}
	
	
	@RequestMapping("/upload2")
	public String upload2() {
		System.out.println("upload");
		return "login";
	}
	
	
	@ResponseBody
	@RequestMapping("/test2")
	public void test2(String sourcePath,String outPath, HttpServletResponse rep) {
		try {

			List<String> sheetNames = new ArrayList<>();
			List<String[][]> valuesList = new ArrayList<>();
			
			HSSFWorkbook wb = null;
			//String filePath = newUrl;
			//String descDir = "zipfile/";
			//String format = filePath.substring(filePath.indexOf(".") + 1);
			

			List<List<String>> filePathList=new ArrayList<>();
			List<String> filePaths=new ArrayList<>();
			FileListUtil.DirAll(new File(sourcePath), sheetNames,valuesList,filePathList,filePaths);
			String[] title = {"序号","年份","证号","名称"};
			for(List<String> fps:filePathList) {
				String [][]values=new String[fps.size()][4];
				for(int z=0;z<fps.size();z++) {
					String fp=fps.get(z);
					String[] fpArr=fp.split("\\\\");
					String year="";
					String num="";
					String name="";
					for(int k=0;k<fpArr.length;k++) {
						String f=fpArr[k];
						if(f.length()<=4&&f.matches("[0-9]+")) {
							year=f;
							if(k+2>=fpArr.length) {
								name=fpArr[k+1];
							}else {
								num=fpArr[k+1];
								name=fpArr[k+2];
							}
						}
					}
					if(!Strings.isNullOrEmpty(year)) {
						values[z][0]=(z+1)+"";
						values[z][1]=year;
						values[z][2]=num;
						values[z][3]=name;
					}
					
				}
				valuesList.add(values);
			}
			
			
			wb = ExcelWriteHelper.getHSSFWorkbooks(sheetNames, title, valuesList, wb);

			OutputStream os = new FileOutputStream(outPath+"/test.xls");
			wb.write(os);

			os.flush();
			os.close();
			
			
			System.err.println("生成成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@ResponseBody
	@RequestMapping("/uploadExcel")
	public ResultType uploadExcel(MultipartHttpServletRequest request) {
		ResultType res = null;
		try {

			MultipartFile file = request.getFile("file");
			MultipartFile file1 = request.getFile("fileId");
			MultipartFile file2 = request.getFile("userupfile");
			MultipartFile file3 = request.getFile("fileToUpload");
			MultipartFile file4 = request.getFile("files");

			excelService.importExcelData(file);
			res = ResultType.getSuccess("上传图片成功");
			// res.setData(path);
			return res;
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.error("上传图片失败", e);
			res = ResultType.getFail("上传图片失败");
		}
		return res;

	}

	@ResponseBody
	@RequestMapping("/upload")
	public ResultType uploadImageList(MultipartHttpServletRequest request) {
		ResultType res = null;
		try {
			StringBuffer path = new StringBuffer();
			List<MultipartFile> files = request.getFiles("file");
			for (MultipartFile file : files) {
				if (path.length() > 0) {
					path.append(",");
				}
				String fileName = file.getOriginalFilename();
				String format = fileName.substring(fileName.lastIndexOf("."));
				fileName = UUID.randomUUID().toString() + format;
				GridFS gridFS = new GridFS(MongoDB.getDB(MongoProperties.DB_NAME), MongoProperties.COLLECTIONS_NAME);
				GridFSFile fsFile = gridFS.createFile(file.getInputStream(), fileName);
				fsFile.save();
				path.append("/" + MongoProperties.NGINX_PATH + "/" + fileName);
			}
			res = ResultType.getSuccess("上传图片成功");
			res.setData(path);
			return res;
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.error("上传图片失败", e);
			res = ResultType.getFail("上传图片失败");
		}
		return res;

	}

	@ResponseBody
	@RequestMapping("/uploadApk")
	public ResultType uploadFile(String fileName, MultipartHttpServletRequest request, HttpServletResponse rep) {
		ResultType res = null;
		fileName = "smoker";
		try {
			MultipartFile file = request.getFile("file");
			MultipartFile file1 = request.getFile("fileId");
			MultipartFile file2 = request.getFile("userupfile");
			MultipartFile file3 = request.getFile("fileToUpload");
			MultipartFile file4 = request.getFile("files");
			System.err.println(file);
			System.err.println(file1);
			System.err.println(file2);
			System.err.println(file3);
			System.err.println(file4);
			if (file.getSize() == 0) {
				throw new RuntimeException("没有文件");
			}
			String filename = file.getOriginalFilename();

			// 获得输入流：
			InputStream input = file.getInputStream();

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("fileSize", file.getSize());

			// 解析apk
			if (".apk".equals(filename.substring(filename.lastIndexOf(".")))) {
				Map<String, Object> xmlMap = ApkReadUtil.readAPK(file.getInputStream());
				map.putAll(xmlMap);
			}
			if (map.get("versionCode") != null) {
				fileName = fileName + "-" + map.get("versionCode");
			}
			String address = "http://" + MongoProperties.MONGO_HOST + upLoadByStream(input, filename, fileName);
			map.put("address", address);

			res = ResultType.getSuccess("成功", map);
		} catch (Exception e) {
			e.printStackTrace();
			res = ResultType.getError(e.getMessage());
			LogUtil.error("无法上传文件", e);
		}
		return res;
	}

	private String upLoadByStream(InputStream input, String fileName, String filename) {

		String randName = UUID.randomUUID().toString();
		String format = "";
		if (fileName != null && fileName.length() > 0 && fileName.lastIndexOf(".") > -1) {
			format = fileName.substring(fileName.lastIndexOf("."));

			// ".apk".equalsIgnoreCase(format)||".jpg".equalsIgnoreCase(format)

			if (".apk".equalsIgnoreCase(format)) {
				if (!"".equals(filename) && filename != null) {
					fileName = filename + format;
				}

			} else {
				throw new RuntimeException("文件格式不正确");
			}

		} else {
			// fileName = filename + MongoProperties.IMG_FORMAT;
		}

		GridFS myFS = new GridFS(MongoDB.getDB(MongoProperties.DB_NAME), MongoProperties.COLLECTIONS_NAME);
		GridFSFile fsFile = myFS.createFile(input, fileName);
		fsFile.save();
		return "/" + MongoProperties.NGINX_PATH + "/" + fileName;

	}

	private String uploadBase64(String path) throws IOException {
		BASE64Decoder decoder = new BASE64Decoder();
		String header = path.substring(0, path.indexOf(","));
		String content = path.substring(path.indexOf(",") + 1);
		String format = "." + header.substring(header.indexOf("/") + 1, header.indexOf(";"));

		byte[] data = decoder.decodeBuffer(content);

		String fileName = UUID.randomUUID().toString() + format;
		GridFS gridFS = new GridFS(MongoDB.getDB(MongoProperties.DB_NAME), MongoProperties.COLLECTIONS_NAME);
		GridFSFile fsFile = gridFS.createFile(new ByteArrayInputStream(data), fileName);
		fsFile.save();
		String newPath = "/" + MongoProperties.NGINX_PATH + "/" + fileName;
		return newPath;
	}

	@ResponseBody
	@RequestMapping("/test")
	public void test(MultipartHttpServletRequest request, HttpServletResponse rep) {
		try {

			List<String> sheetNames = new ArrayList<>();
			List<String[][]> valuesList = new ArrayList<>();
			MultipartFile file = request.getFile("file");
			InputStream in=file.getInputStream();
			String newUrl = file.getOriginalFilename();
			File newFile = new File(newUrl);
			/*
			try {
				OutputStream out = new FileOutputStream(newFile);
				// InputStream in=new FileInputStream(new File(apkUrl));
				int i = in.read();
				while (i != -1) {
					// System.out.println(i);
					out.write(i);
					i = in.read();
				}
				out.close();
				in.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
*/
			HSSFWorkbook wb = null;
			String filePath = newUrl;
			String descDir = "zipfile/";
			String format = filePath.substring(filePath.indexOf(".") + 1);
			if (format.equalsIgnoreCase("rar")) {
				//File rarFile = new File(filePath);
				//ZipUtil.unRar(newFile, descDir);
				ZipUtil.unRarInputStream((FileInputStream)in, descDir);

			} else if (format.equalsIgnoreCase("zip")) {
				
				
				try {
					OutputStream out = new FileOutputStream(newFile);
					// InputStream in=new FileInputStream(new File(apkUrl));
					int i = in.read();
					while (i != -1) {
						// System.out.println(i);
						out.write(i);
						i = in.read();
					}
					out.close();
					in.close();
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
				
				ZipUtil.unZipFiles(newFile, descDir);
			}

			List<List<String>> filePathList=new ArrayList<>();
			List<String> filePaths=new ArrayList<>();
			FileListUtil.DirAll(new File(descDir), sheetNames,valuesList,filePathList,filePaths);
			String[] title = {"序号","年份","证号","名称"};
			for(List<String> fps:filePathList) {
				String [][]values=new String[fps.size()][4];
				for(int z=0;z<fps.size();z++) {
					String fp=fps.get(z);
					String[] fpArr=fp.split("\\\\");
					String year="";
					String num="";
					String name="";
					for(int k=0;k<fpArr.length;k++) {
						String f=fpArr[k];
						if(f.matches("[0-9]+")) {
							year=f;
							if(k+2>=fpArr.length) {
								name=fpArr[k+1];
							}else {
								num=fpArr[k+1];
								name=fpArr[k+2];
							}
						}
					}
					if(!Strings.isNullOrEmpty(year)) {
						values[z][0]=(z+1)+"";
						values[z][1]=year;
						values[z][2]=num;
						values[z][3]=name;
					}
					
				}
				valuesList.add(values);
			}
			
			
			

			wb = ExcelWriteHelper.getHSSFWorkbooks(sheetNames, title, valuesList, wb);

			// 响应到客户端
			try {
				setResponseHeader(rep, newUrl.substring(0,newUrl.indexOf("."))+".xls");
				OutputStream os = rep.getOutputStream();
				wb.write(os);
				os.flush();
				os.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=utf-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
